import React, { useState } from 'react';
import { Card, Table, Button, Input, Select, Space, Pagination, Modal, message, Descriptions } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { FileTextOutlined, UserOutlined, CalendarOutlined, AppstoreOutlined, ClusterOutlined, TagOutlined, HomeOutlined, ApartmentOutlined } from '@ant-design/icons';

const { Option } = Select;

export default function ContractManage() {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [searchTenant, setSearchTenant] = useState("");
  const [searchBuilding, setSearchBuilding] = useState("");
  const [searchRoom, setSearchRoom] = useState("");
  const [searchType, setSearchType] = useState("");
  const [searchStatus, setSearchStatus] = useState("");
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [currentDetail, setCurrentDetail] = useState(null);
  const initialData = [
  { key: 1, tenant: '杭州公感科技有限公司', building: 'C2幢', room: '206', type: '续签', status: '生效中', signDate: '2020-05-17', expireDate: '2022-01-23' },
  { key: 2, tenant: '杭州橙云科技有限公司', building: 'A1幢', room: '308', type: '新签', status: '生效中', signDate: '2020-08-17', expireDate: '2022-01-23' },
  { key: 3, tenant: '杭州橙迹科技有限公司', building: 'B2幢', room: '507', type: '续签', status: '生效中', signDate: '2021-08-02', expireDate: '2022-01-23' },
  { key: 4, tenant: '南宁市可达靓成乐有限公司', building: 'B2幢', room: '801', type: '续签', status: '到期', signDate: '2020-08-08', expireDate: '2022-01-23' },
  { key: 5, tenant: '杭州超梦科技有限公司', building: 'B2幢', room: '1202', type: '续签', status: '退租', signDate: '2020-11-17', expireDate: '2022-01-23' },
  { key: 6, tenant: '杭州氢雾度东际科技有限公司', building: 'A1幢', room: '1406', type: '续签', status: '生效中', signDate: '2021-12-17', expireDate: '2022-01-23' },
  { key: 7, tenant: '喵典典（杭州）科技有限公司', building: 'C2幢', room: '903', type: '续签', status: '生效中', signDate: '2021-12-17', expireDate: '2022-01-23' },
  { key: 8, tenant: '杭州依依然商务服务有限公司', building: 'B2幢', room: '706', type: '新签', status: '到期', signDate: '2020-08-05', expireDate: '2022-01-23' },
  { key: 9, tenant: '杭州溢溪投资管理有限公司', building: 'B2幢', room: '604', type: '续签', status: '到期', signDate: '2020-08-04', expireDate: '2022-01-23' },
  { key: 10, tenant: '杭州林涛工程机械科技有限公司', building: 'B1幢', room: '302', type: '新签', status: '退租', signDate: '2020-09-11', expireDate: '2022-01-23' },
];
  const [tableData, setTableData] = useState(initialData);
  const [filteredData, setFilteredData] = useState(initialData);
  const navigate = useNavigate();
  const location = useLocation();

  // 新增合同后自动添加
  React.useEffect(() => {
    if (location.state && location.state.newContract) {
      setTableData(prev => [location.state.newContract, ...prev]);
      setFilteredData(prev => [location.state.newContract, ...prev]);
      // 清除state避免重复添加
      window.history.replaceState({}, document.title);
    }
  }, [location.state]);

  // 单个删除
  const handleDelete = (key) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条合同吗？',
      onOk() {
        const newData = tableData.filter(item => item.key !== key);
        setTableData(newData);
        setFilteredData(newData);
        setSelectedRowKeys(selectedRowKeys.filter(k => k !== key));
        message.success('删除成功');
      },
    });
  };

  const columns = [
    { title: '租户名称', dataIndex: 'tenant', key: 'tenant', width: 200 },
    { title: '所属楼宇', dataIndex: 'building', key: 'building', width: 100 },
    { title: '房间名称', dataIndex: 'room', key: 'room', width: 100 },
    { title: '合同类型', dataIndex: 'type', key: 'type', width: 100 },
    { title: '合同状态', dataIndex: 'status', key: 'status', width: 100 },
    { title: '签约时间', dataIndex: 'signDate', key: 'signDate', width: 120 },
    { title: '到期时间', dataIndex: 'expireDate', key: 'expireDate', width: 120 },
    { title: '操作', key: 'action', width: 120, render: (_, record) => (
        <Space>
          <a onClick={() => { setCurrentDetail(record); setDetailModalVisible(true); }}>详情</a>
          <a style={{color:'#f5222d'}} onClick={() => handleDelete(record.key)}>删除</a>
        </Space>
      ) },
  ];

  // 查询功能
  const handleSearch = () => {
    setFilteredData(
      tableData.filter(item => {
        const matchTenant = searchTenant ? item.tenant.includes(searchTenant) : false;
        const matchBuilding = searchBuilding ? item.building === searchBuilding : false;
        const matchRoom = searchRoom ? item.room.includes(searchRoom) : false;
        const matchType = searchType ? item.type === searchType : false;
        const matchStatus = searchStatus ? item.status === searchStatus : false;
        return matchTenant || matchBuilding || matchRoom || matchType || matchStatus;
      })
    );
  };

  // 重置功能
  const handleReset = () => {
    setSearchTenant("");
    setSearchBuilding("");
    setSearchRoom("");
    setSearchType("");
    setSearchStatus("");
    setFilteredData(tableData);
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的合同');
      return;
    }
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 条合同吗？`,
      onOk() {
        const newData = tableData.filter(item => !selectedRowKeys.includes(item.key));
        setTableData(newData);
        setFilteredData(newData);
        setSelectedRowKeys([]);
        message.success('删除成功');
      },
    });
  };

  return (
    <div style={{padding:32, background:'#f5f7fa', minHeight:'100vh'}}>
      <Card style={{maxWidth:1300, margin:'0 auto', borderRadius:12, boxShadow:'0 2px 8px rgba(0,0,0,0.04)'}}>
        <div style={{display:'flex', alignItems:'center', marginBottom:24}}>
          <Button onClick={()=>navigate('/dashboard/enterprise')} style={{marginRight:16, borderRadius:6}}>返回</Button>
          <div style={{fontWeight:700, fontSize:20, display:'flex', alignItems:'center'}}>
            <div style={{width:4, height:22, background:'#3B5BDB', borderRadius:2, marginRight:10}}></div>
            合同签订管理
          </div>
          <div style={{flex:1}}></div>
          <Button type="primary" style={{borderRadius:6, width:90, marginRight:8}} onClick={()=>navigate('/business/contract/create')}>新增</Button>
          <Button danger style={{borderRadius:6, width:110}} onClick={handleBatchDelete}>批量删除</Button>
        </div>
        <div style={{marginBottom:20, display:'flex', gap:16, alignItems:'center', background:'#fafbfc', padding:'18px 18px 0 18px', borderRadius:8}}>
          <Input value={searchTenant} onChange={e=>setSearchTenant(e.target.value)} placeholder="请输入租户名称" style={{width:220, borderRadius:6}} allowClear />
          <Select value={searchBuilding} onChange={v=>setSearchBuilding(v)} placeholder="请选择楼宇" style={{width:180, borderRadius:6}} allowClear>
            <Option value="A1幢">A1幢</Option>
            <Option value="B1幢">B1幢</Option>
            <Option value="B2幢">B2幢</Option>
            <Option value="C2幢">C2幢</Option>
          </Select>
          <Input value={searchRoom} onChange={e=>setSearchRoom(e.target.value)} placeholder="请输入房间名称" style={{width:180, borderRadius:6}} allowClear />
          <Select value={searchType} onChange={v=>setSearchType(v)} placeholder="请选择合同属性" style={{width:180, borderRadius:6}} allowClear>
            <Option value="新签">新签</Option>
            <Option value="续签">续签</Option>
          </Select>
          <Select value={searchStatus} onChange={v=>setSearchStatus(v)} placeholder="请选择合同状态" style={{width:180, borderRadius:6}} allowClear>
            <Option value="生效中">生效中</Option>
            <Option value="到期">到期</Option>
            <Option value="退租">退租</Option>
          </Select>
          <Button type="primary" style={{borderRadius:6, width:90}} onClick={handleSearch}>查询</Button>
          <Button style={{borderRadius:6, width:90}} onClick={handleReset}>重置</Button>
        </div>
        <Table
          rowSelection={{selectedRowKeys,onChange:setSelectedRowKeys}}
          columns={columns}
          dataSource={filteredData}
          pagination={false}
          bordered
          style={{background:'#fff', borderRadius:8, marginTop:16}}
        />
        <div style={{marginTop:24, textAlign:'right'}}>
          <Pagination total={100} pageSize={10} showSizeChanger={false} />
        </div>
      </Card>
      <Modal
        title={null}
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={600}
        bodyStyle={{padding:32, borderRadius:16, background:'#f7f9fa'}}
      >
        {currentDetail && (
          <div style={{ background:'#fff', borderRadius:12, boxShadow:'0 2px 8px rgba(0,0,0,0.06)', padding:32 }}>
            <div style={{ display:'flex', alignItems:'center', marginBottom:24 }}>
              <FileTextOutlined style={{ fontSize:32, color:'#3B5BDB', marginRight:16 }} />
              <div>
                <div style={{ fontSize:22, fontWeight:700, color:'#222' }}>{currentDetail.tenant}</div>
                <div style={{ color:'#888', fontSize:14, marginTop:4 }}>{currentDetail.building} · {currentDetail.room}</div>
              </div>
            </div>
            <Descriptions column={1} labelStyle={{fontWeight:600, color:'#555'}} contentStyle={{color:'#222'}}>
              <Descriptions.Item label={<span><HomeOutlined style={{marginRight:6}}/>所属楼宇</span>}>{currentDetail.building}</Descriptions.Item>
              <Descriptions.Item label={<span><ApartmentOutlined style={{marginRight:6}}/>房间名称</span>}>{currentDetail.room}</Descriptions.Item>
              <Descriptions.Item label={<span><TagOutlined style={{marginRight:6}}/>合同类型</span>}>{currentDetail.type}</Descriptions.Item>
              <Descriptions.Item label={<span><AppstoreOutlined style={{marginRight:6}}/>合同状态</span>}>{currentDetail.status}</Descriptions.Item>
              <Descriptions.Item label={<span><CalendarOutlined style={{marginRight:6}}/>签约时间</span>}>{currentDetail.signDate}</Descriptions.Item>
              <Descriptions.Item label={<span><CalendarOutlined style={{marginRight:6}}/>到期时间</span>}>{currentDetail.expireDate}</Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Modal>
    </div>
  );
} 